<template>
  <div class="InverterAnaly">
    <div class="leftbox">
      <HavucheckTree @handClick="handClick" @chushihua="chushihua"></HavucheckTree>
    </div>
    <div class="rightbox">
      <div class="righttop">
        <el-form ref="form" label-position="left" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="7" style="display:flex;margin-top: 4px;">
                  <el-radio-group v-model="radio3" size="small" style="margin-right: 20px;">
                    <el-radio-button label="1">日</el-radio-button>
                    <el-radio-button label="2">月</el-radio-button>
                    <el-radio-button label="3">年</el-radio-button>
                  </el-radio-group>
                  <el-date-picker style="flex:1;" v-if="radio3=='1'" v-model="value1" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" size="small"></el-date-picker>
                  <el-date-picker style="flex:1;" v-if="radio3=='2'" v-model="value2" type="month" value-format="yyyy-MM" placeholder="选择月" size="small"></el-date-picker>
                  <el-date-picker style="flex:1;" v-if="radio3=='3'" v-model="value3" type="year" value-format="yyyy" placeholder="选择年" size="small"></el-date-picker>
                </el-col>
                <el-col :span="17" style="text-align: right;">
                <el-form-item label="">
                  <el-button size="small" @click="chongzhi">重 置</el-button>
                  <el-button size="small" type="primary" @click="gettablelist">查 询</el-button>
                </el-form-item>
              </el-col>
            </el-row>
        </el-form>
      </div>
      <div class="rightbody">
        <div class="title">
          <div>逆变器对标分析</div>
          <div><TopTile  @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile></div>
        </div>
        <div class="echandtab">
          <div class="tongbiech" ref="tongbiech"></div>
          <div class="tongbiech" >
              <el-table
              :data="tableData"
              :size="issize"
              border
              ref="table"
              :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
              v-loading="loading"
              height="calc(100% - 1px)"
              style="width: 100%">
              <template slot="empty">
                <el-empty description="暂无数据"></el-empty>
              </template>
              <el-table-column
              v-if="tableData.length"
                prop="date"
                label="日期"
                fixed
                width="150"
                align="center">
              </el-table-column>
              <el-table-column :label="item.label" v-for="(item,index) in tableColumns" :key="index">
                <el-table-column 
                  v-for="(items,indexs) in item.children"
                  :key="indexs+1"
                  align="right"
                  :prop="items.prop"
                  :label="items.label">
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import HavucheckTree from '../component/HavucheckTree.vue'
import * as echarts from 'echarts';
import TopTile from '@/components/TopTitle/index.vue'
import TableColumn from '@/components/Table/index.vue'
import { exportexcel } from '@/utils/excel'
import {getduibiaoqixianapi,getduibiaotableapi} from '@/api/Photovoltaic/analysis/InverterAnaly'
export default {
  name: 'CallPoliceINDEX',
  components: {
    TopTile,
    TableColumn,
    HavucheckTree
  },
  data() {
    return {
      radio3: '1',
      value1:[],
      value2:[],
      value3: [],
      loading: false,
      issize: 'medium',
      tableData: [],
      threelist: [],
      tableColumns:[]
    };
  },

  mounted() {
    this.gettime()
  },

  methods: {
    // 重置
    chongzhi() { 
      this.radio3 = '1'
      this.gettime()
      this.gettablelist()
    },
    chushihua(val) {
      this.handClick(val)
    },
    //获取数据
    async gettablelist() {
      if (this.threelist.length) {
        this.getfadianlv()
        this.gettablist()
      } else {
        this.tableColumns=[]
        this.tableData = []
        this.getfadianlv(true)
        this.$message.warning('请先选择数据')
      }

    },
    // 树节点点击
    handClick(val) {
      this.threelist = val
      this.gettablelist()
    },
    // 获取表格数据
    async gettablist() {
      this.loading=true
      const contrastString =[]
        this.threelist.map(ele =>contrastString.push(ele.id) )
      const { data: { list } } = await getduibiaotableapi({
        dateString:this.radio3=='1'?this.value1:this.radio3=='2'?this.value2:this.value3,
        dateType:this.radio3,contrastString:contrastString.join(',')
      })
      let tableData = [];
      list.forEach(item => {
        let rowData = { date: item.dateTime };
        item.inverterPowerList.forEach(inverter => {
          rowData[inverter.name + "_quantity"] = inverter.quantity;
          rowData[inverter.name + "_power"] = inverter.power;
        });
        tableData.push(rowData);
      });
      // 构建 el-table 表格
      let tableColumns = [];
      list[0]?.inverterPowerList.forEach(inverter => {
        let inverterColumn = {
          label: inverter.name,
          children: [
            {
              prop: inverter.name + "_quantity",
              label: "发电量(kWh)"
            },
            {
              prop: inverter.name + "_power",
              label: "功率(kW)"
            }
          ]
        };
        tableColumns.push(inverterColumn);
      });
      this.tableColumns=tableColumns
      this.tableData = tableData
      this.$nextTick(()=>this.$refs.table.doLayout())
      this.loading=false
    },
    // 获取电量图表
    async getfadianlv(flag) {
      var chartDom = this.$refs.tongbiech
      var myChart = echarts.init(chartDom);
      var option;
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        target: chartDom
      });
      const contrastString = []
      this.threelist.map(ele => contrastString.push(ele.id))
      if (!flag) {
        const { data: { list } } = await getduibiaoqixianapi({
        dateString:this.radio3=='1'?this.value1:this.radio3=='2'?this.value2:this.value3,
        dateType:this.radio3,contrastString:contrastString.join(',')
      })
      var timePoints =[]
      for (let i = 0; i < list.length; i++) {
          if (list[i].datalist.length > 0) {
              list[i].datalist.forEach(data => {
                timePoints.push(data.timeReading);
              });
              break;
          }
      }
      var series = list.map(ele => {
        const str=ele.name.slice(-2)
         return {
            name: ele.name,
           type: str == '电量' ? 'bar' : 'line',
           smooth: true,
            yAxisIndex: str == '电量' ? null : 1,
            data: ele.datalist.map(ele => ele.valueReading)
          }
      })
      }

      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        grid: {
          left: '2%',
          right: '1%',
          bottom: '3%',
          containLabel: true
        },
        legend: {},
        xAxis: [
          {
            type: 'category',
            data:flag?[]:timePoints,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name:'电量(kWh)'
          },
          {
            type: 'value',
            name:'负荷(kW)'
          }
        ],
        series: flag?[]:series
      };
      myChart.clear();
      option && myChart.setOption(option);
      loading.close()
    },
         // 调节表格密度
  command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 导出
    daochu() {
      const contrastString =[]
        this.threelist.map(ele =>contrastString.push(ele.id) )
      exportexcel('pes-microservice-biz/pvm/inverter/benchmarking/data/exportExcel',{
        dateString:this.radio3=='1'?this.value1:this.radio3=='2'?this.value2:this.value3,
        dateType:this.radio3,contrastString:contrastString.join(',')
      },'逆变器对标分析')
    },
    // 刷新列表
    shuaxin() {
      this.gettablelist()
      this.$message.success('列表刷新成功')
    },
    // 获取当前时间戳
    gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month = mon < 10 ? '0' + mon : mon
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() //日
      this.$set(this,'value1',year+'-'+month+'-'+day)
      this.$set(this,'value2',year+'-'+month)
      this.$set(this,'value3',year.toString())
    },
  },
};
</script>

<style scoped>
.InverterAnaly{
  height: 100%;
  padding: 10px;
  display: flex;
  .leftbox{
    width: 300px;
    padding: 20px;
    background-color: #fff;
    margin-right: 10px;
  }
  .rightbox{
    width: calc(100% - 310px);
    height: 100%;
    .righttop{
      height:80px;
      background-color: #fff;
      padding: 20px;
      margin-bottom: 10px;
    }
    .rightbody{
      height: calc(100% - 90px);
      padding: 20px;
      background-color: #fff;
      .title{
        margin-bottom: 10px;
        display:flex;
        justify-content:space-between;
      }
    .echandtab{
       height: 95%;
       .tongbiech{
          height: 50%;
        }
      }
    }
  }
}
</style>